package com.maple.interceptor;

import com.maple.constant.JwtClaimsConstant;
import com.maple.mapper.UserMapper;
import com.maple.properties.JwtProperties;
import com.maple.utils.JwtUtil;
import com.maple.utils.ThreadLocalUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


@Slf4j
@Configuration
public class JwtUserInterceptor implements HandlerInterceptor {


    @Autowired
    JwtProperties jwtProperties;


    /**
     * 令牌拦截器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断是否是Controller方法
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        String token = request.getHeader(jwtProperties.getUserTokenName());
        log.info("开始令牌校验：{}",token);

        try{
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
            ThreadLocalUtils.setCurrentId(userId);
            log.info("用户id为{}",userId);
            return true;
        } catch (Exception e){
            log.info("令牌校验错误");

            return false;
        }
    }
    
    
}
